package dev.loong.boot3.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import dev.loong.boot3.pojo.User;
import dev.loong.boot3.service.DocUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DocUserServiceImpl implements DocUserService {
    private final MongoTemplate mongoTemplate;
    @Autowired
    public DocUserServiceImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
    @Override
    public void saveUser(User user) {
        this.mongoTemplate.save(user);
    }

    @Override
    public User getUser(Long id) {
        return this.mongoTemplate.findById(id, User.class);
    }

    @Override
    public List<User> findUser(String userName, String note, int skip, int limit) {
        var criteria = Criteria.where("userName").regex(userName).and("note").regex(note);
        return this.mongoTemplate.find(Query.query(criteria).limit(limit).skip(skip), User.class);
    }

    @Override
    public DeleteResult deleteUser(Long id) {
        return this.mongoTemplate.remove(Query.query(Criteria.where("id").is(id)), User.class);
    }

    @Override
    public UpdateResult updateUser(Long id, String userName, String note) {
        return this.mongoTemplate.updateFirst(
                Query.query(Criteria.where("id").is(id)),
                Update.update("userName", userName).set("note", note), User.class);
    }
}
